package com.feihong.yw189.activity.dingdan;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.feihong.yw189.R;
import com.feihong.yw189.activity.base.BaseActivity;
import com.feihong.yw189.http.HttpTools;
import com.feihong.yw189.http.RefreshToken;
import com.feihong.yw189.message.LoginMessage;
import com.feihong.yw189.utils.ThreadPoolManager;
import com.feihong.yw189.utils.UserLoginInfo;
import com.feihong.yw189.view.WebView4Scroll;
import com.just.agentweb.AgentWeb;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class KuanDaiDetailsActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.rl_goback)
    RelativeLayout rlGoback;
    @BindView(R.id.iv_lin)
    ImageView ivLin;
    @BindView(R.id.webviewframe)
    RelativeLayout webviewFrame;
    @BindView(R.id.swiperefreshlayout)
    SwipeRefreshLayout mswiperefreshlayout;
    //
    public AgentWeb mAgentWeb;
    private Unbinder unbinder;
    private String orderSn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_webview);
        unbinder = ButterKnife.bind(this);

        orderSn = getIntent().getStringExtra("order_sn");
        if(!TextUtils.isEmpty(orderSn)){

        }

        refreshToken();

        initView();
    }

    @Override
    public void setTheme() {

    }

    private Handler mHandler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case REFRESH_TOKEN_WHAT:
                    bindData();
                    break;
                default:break;
            }
        }
    };
    /**
     * 刷新token
     */
    private static final int REFRESH_TOKEN_WHAT = 10;
    private void refreshToken() {
        ThreadPoolManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                boolean result = RefreshToken.getInstance().getRequestGetToken();
                Message message = Message.obtain();
                message.what = REFRESH_TOKEN_WHAT;
                mHandler.sendMessage(message);
            }
        });
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    public void initView() {
        setBackButtonFinish();
        setPageTitle("订单详情");
        ivLin.setVisibility(View.GONE);

        // AgentWeb 保持了 WebView 的使用 ，
        //设置刷新时动画的颜色，可以设置4个
        mswiperefreshlayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        mswiperefreshlayout.setColorSchemeResources(R.color.appRed,
                android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        mswiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                bindData();
            }
        });

        mswiperefreshlayout.setRefreshing(true);
    }

    private void bindData() {
        if (mAgentWeb == null) {
            WebView4Scroll webView4Scroll = new WebView4Scroll(getActivity(), mswiperefreshlayout);
            webView4Scroll.setVerticalScrollBarEnabled(false);
            mAgentWeb = AgentWeb.with(this)
                    .setAgentWebParent(webviewFrame, new LinearLayout.LayoutParams(-1, -1))
                    .useDefaultIndicator()
                    .setWebViewClient(mWebViewClient)
                    .setMainFrameErrorView(R.layout.agentweb_errorlayout, R.id.agentweb_re_query_data_layout)
                    .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                    .createAgentWeb()
                    .ready()
                    .go(""+ HttpTools.KUANDAI_DETAILS+"? token=" + UserLoginInfo.getUserLoginInfoInstance().getUserToken()+"? order_sn="+orderSn);
            //  .go(HttpTools.ORDER_LIST_PAGE + "? token=" + UserLoginInfo.getUserToken());
            mAgentWeb.getAgentWebSettings().getWebSettings().setGeolocationEnabled(false);

            //屏蔽长按弹出复制按钮
            mAgentWeb.getWebCreator().getWebView().setOnLongClickListener(new View.OnLongClickListener() {

                @Override
                public boolean onLongClick(View v) {
                    return true;
                }
            });

        } else {
            mAgentWeb.getWebCreator().getWebView().setVisibility(View.VISIBLE);
            mAgentWeb.getUrlLoader().reload();
        }
    }

    //WebViewClient
    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            showSystemToast(url);
            return true;
            // return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {

            return true;
            // return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mswiperefreshlayout.setRefreshing(false);
        }

    };
    @OnClick({R.id.iv_back, R.id.rl_goback})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_goback:
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();

        if(mHandler != null && mHandler.getLooper() == Looper.getMainLooper()){
            mHandler.removeCallbacksAndMessages(null);
        }
    }
}
